# -*- coding: utf-8 -*-
# created on 2016/04/12

from sympy import sympify, Integer
from sympy.abc import x, n
from mathsolver.functions.base.base import BaseFunction
from mathsolver.functions.base.objects import BaseNumber
from mathsolver.functions.hanshu.helper import check_inter, check_func
from mathsolver.functions.hanshu.jiou_qiuzhi import JiOuQiuZhi
from mathsolver.functions.hanshu.zhouqi import is_fx, has_f
from mathsolver.functions.hanshu.zhouqi_qiuzhi import ZhouQiQiuZhiJieXiShi
from mathsolver.functions.hanshu.hanshu_inference2 import HanShuQiuZhi2
from mathsolver.functions.hanshu.hanshu_inference import HanShuQiuZhi


def is_zhouqi_dingyishi(eq):
    """判断 eq 是否是周期定义式：f(x) = f(x+n*T) 如果满足返回 T 的值"""
    eq_lhs, eq_rhs = eq
    # 左边是 f(x) 右边是 f(*)
    if is_fx(eq_lhs) and has_f(eq_rhs):
        # (2*n, x)
        i1, i2 = eq_rhs.args[0].as_independent(x)
        if i2 == x and i1.has(n):
            return i1 / n
        if i2 == x and isinstance(i1, Integer):
            return i1


def is_ji_dingyishi(eq):
    """判断 eq 是否是奇函数定义式"""
    return eq == sympify('(f(x), -f(-x))')


def is_ou_dingyishi(eq):
    """判断 eq 是否是偶函数定义式"""
    return eq == sympify('Eq(f(x), f(-x))')


def is_jiou_dingyishi(eq):
    """判断 eq 是否是 奇/偶 函数定义式"""
    return is_ji_dingyishi(eq) or is_ou_dingyishi(eq)


class ZhongHeQiuZhi(BaseFunction):
    """函数性质综合求值"""

    def solver(self, *args):
        if len(args) == 3:
            # solve_hanshu_qiuzhi 输入3个
            eq, io_value, funcname = args
            # 函数性质综合求函数的值——函数值
            return HanShuQiuZhi().solver(eq, io_value, funcname)
        eq, any_it_bl_ineq, func, funcname = args[0], args[1], check_func(args[2]), args[3]

        # 函数性质综合求函数的值
        if isinstance(eq, list):
            return HanShuQiuZhi2().solver(eq, check_inter(any_it_bl_ineq), func, funcname)
        # 函数周期性求函数的值——函数解析式
        elif is_zhouqi_dingyishi(eq):
            zhouqi_t = is_zhouqi_dingyishi(eq)
            return ZhouQiQiuZhiJieXiShi().solver(func, check_inter(any_it_bl_ineq), BaseNumber(zhouqi_t), funcname)
        # 函数奇偶性求值
        elif is_jiou_dingyishi(eq):
            return JiOuQiuZhi().solver(eq, any_it_bl_ineq, func, funcname)
        else:
            raise RuntimeError("补充 %s 类型的原函数" % str(eq))


if __name__ == '__main__':
    pass
